package com.ysq.www.common.utils;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import java.util.UUID;

public class Comm {

    /**
     * 获取当前日期
     * @return
     */
    public static Date getNow(){
        return Calendar.getInstance().getTime();
    }

    /**
     * 字符串截取
     * (index=0,从0的位置开始截取，否则从大于0的位置截取)
     */
    public static String subString(String str,char ch, int index) {
        String result = null;
        if (str != null && str != "") {
            if (index == 0) {
                for (int i = 0; i < str.length(); i++) {
                    if (str.charAt(i) == ch) {
                        result = str.substring(0, i);
                    }
                }
            }else{
                for (int i = 0; i < str.length(); i++) {
                    if (str.charAt(i) == ch) {
                        result = str.substring(i+1);
                    }
                }
            }

        }
        return result;
    }

    /**
     * 得到系统时间 0:显示日期和时间,1:日期和时间加周期，2:简版日期时间和毫秒数
     */
    public static String getSysDate(int type) {
        SimpleDateFormat dateFormat = null;
        switch (type) {
            case 0:
                dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                break;
            case 1:
                dateFormat = new SimpleDateFormat("yyyy年MM月dd日 E HH:mm:ss");
                break;
            case 2:
                dateFormat = new SimpleDateFormat("yyMMddHHmmssSSS");
                break;
            case 3:
                dateFormat = new SimpleDateFormat("yyyyMMdd");
                break;
            case 4:
                dateFormat = new SimpleDateFormat("yyMdHHmmssSS");
                break;
            case 5:
                dateFormat = new SimpleDateFormat("yyyy年MM月dd日  HH:mm:ss");
                break;
            case 6:
                dateFormat = new SimpleDateFormat("HH:mm");
                break;
            case 7:
                dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                break;
            case 8:
                dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
                break;
            case 9:
                dateFormat = new SimpleDateFormat("yyMMdd");
        }
        return dateFormat.format(Calendar.getInstance().getTime());
    }

    /**
     * 将日期格式转成长字符串格式：yyyy-MM-dd HH:mm:ss
     * @param date
     * @return String
     */
    public static String  dateToLongStr(Date date){
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(date);
        return dateString;
    }


    /* 将短时间格式时间转换为字符串 yyyy-MM-dd
    * @param dateDate
    * @param k
    * @return
    */
    public static String dateToStr(Date dateDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = formatter.format(dateDate);
        return dateString;
    }

    /**
     * 转换日期字符串格式，将yyyy-MM-dd HH:mm:ss格式日期字符串转为yyMMdd
     * @param dateStr
     * @return
     * @throws ParseException
     */
    public static String changeDateFormat(String dateStr) throws ParseException{
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyMMdd");
        return sdf1.format(sdf.parse(dateStr));
    }

    /**
     * 字符串不能为空的终极判断 父方法
     *
     * @param obj
     * @return
     */
    public static String isNULLS(Object obj) {
        return (obj != null && !obj.equals("null")) ? obj.toString() : "";
    }

    /**
     * 说明:(字符串不能为空的终极判断 ) 作者: y1
     */
    public static String isNULL2(Object obj, String defaVal) {
        String result = isNULLS(obj);
        return result.length() > 0 ? result : defaVal;
    }

    /**
     * 数字字符串转成Double
     * 如果Double.parseDouble(null);这个是报空指针异常
     */
    public static double parseDouble(Object obj) {
        try {
            String result = isNULLS(obj);
            return result.length() > 0 ? Double.parseDouble(result) : 0;
        } catch (NumberFormatException e) {
            return 0;
        }
    }
    public static double parseDouble(Object obj, double defaVal) {
        try {
            String result = isNULLS(obj);
            return result.length() > 0 ? Double.parseDouble(result) : defaVal;
        } catch (NumberFormatException e) {
            return defaVal;
        }
    }

    /**
     * 数字字符串转成Int
     * 如果Integer.parseInt(null);这个是报空指针异常
     */
    public static int parseInt(Object obj) {
        try {
            String result = isNULLS(obj);
            return result.length() > 0 ? Integer.parseInt(result) : 0;
        } catch (NumberFormatException e) {
            return 0;
        }
    }

    /**
     * 将长时间格式字符串转换为时间 yyyy-MM-dd HH:mm:ss
     *
     * @param strDate
     * @return
     */
     public static Date strToDateLong(String strDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ParsePosition pos = new ParsePosition(0);
        Date strtodate = formatter.parse(strDate, pos);
        return strtodate;
     }

    /**
     * 将长时间格式字符串转换为时间 yyyy-MM-dd
     *
     * @param strDate
     * @return
     */
    public static Date strToDateShort(String strDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        ParsePosition pos = new ParsePosition(0);
        Date strtodate = formatter.parse(strDate, pos);
        return strtodate;
    }

    /**
     * 得到几天前的时间
     * @param d
     * @param day
     * @return
     */
    public static Date getDateBefore(Date d,int day){
        Calendar now =Calendar.getInstance();
        now.setTime(d);
        now.set(Calendar.DATE,now.get(Calendar.DATE)-day);
        return now.getTime();
    }

    /**
     * 得到几天后的时间
     * @param d
     * @param day
     * @return
     */
    public static Date getDateAfter(Date d,int day){
        Calendar now =Calendar.getInstance();
        now.setTime(d);
        now.set(Calendar.DATE,now.get(Calendar.DATE)+day);
        return now.getTime();
    }


    /**
     * 获取当天0点0分0秒（00:00:00）
     *
     * @return
     */
    public static String getTimesMorning() {
        Calendar cal = Calendar.getInstance();
        cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        Date beginOfDate = cal.getTime();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return formatter.format(beginOfDate);
    }

    /**
     * 获取当天0点0分0秒（00:00:00）
     *
     * @return
     */
    public static Date getTimesStart() {
        Calendar cal = Calendar.getInstance();
        cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        Date beginOfDate = cal.getTime();
        return beginOfDate;
    }

    /**
     * 获取当天23点59分59秒
     */
    public static Date getTimesEnd(){
        Calendar calendar = Calendar.getInstance();
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH),
                23, 59, 59);
        Date endOfDate = calendar.getTime();
        return endOfDate;
    }

    /**
     * 获得验证码
     *
     * @return
     */
    public static String getCode() {
        Random r = new Random();
        int code = 0;
        while (true) {
            int x = r.nextInt(999999);
            if (x > 99999) {
                code = x;
                break;
            }
        }
        return Integer.toString(code);
    }

    //length用户要求产生字符串的长度
    public static String getRandomString(int length){
        String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random=new Random();
        StringBuffer sb=new StringBuffer();
        for(int i=0;i<length;i++){
            int number=random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }

    //价格类型为BigDecimal 换算成分
    public static BigDecimal intRideToBigDecimal(BigDecimal b,int i){
        return b.multiply(new BigDecimal(i));
    }

    //判断验证码是否过期（5分钟）
    public static boolean compareTime(Date d1){
        Calendar dateOne=Calendar.getInstance();
        Calendar dateTwo=Calendar.getInstance();
        dateOne.setTime(new Date());//设置为当前系统时间
        dateTwo.setTime(d1); //获取数据库中的时间
        long timeOne=dateOne.getTimeInMillis();
        long timeTwo=dateTwo.getTimeInMillis();
        long minute=(timeOne-timeTwo)/(1000*60);//转化minute
        //判断时间是否大于5分钟
        if(minute > 5){
            //大于5分钟
            return false;
        }
        return true;
    }

    /**
     * 两个日期相减得到的相隔天数
     * @param startDate
     * @param endDate
     * @return
     */
    public static Long getDaysBetween(Date startDate, Date endDate) {
        Calendar fromCalendar = Calendar.getInstance();
        fromCalendar.setTime(startDate);
        fromCalendar.set(Calendar.HOUR_OF_DAY, 0);
        fromCalendar.set(Calendar.MINUTE, 0);
        fromCalendar.set(Calendar.SECOND, 0);
        fromCalendar.set(Calendar.MILLISECOND, 0);

        Calendar toCalendar = Calendar.getInstance();
        toCalendar.setTime(endDate);
        toCalendar.set(Calendar.HOUR_OF_DAY, 0);
        toCalendar.set(Calendar.MINUTE, 0);
        toCalendar.set(Calendar.SECOND, 0);
        toCalendar.set(Calendar.MILLISECOND, 0);

        return (toCalendar.getTime().getTime() - fromCalendar.getTime().getTime()) / (1000 * 60 * 60 * 24);
    }

    /**
     * 计算年龄
     */
    public static int getAgeByBirth(Date birthDay) throws ParseException {
        int age = 0;
        Calendar cal = Calendar.getInstance();
        if (cal.before(birthDay)) { //出生日期晚于当前时间，无法计算
            throw new IllegalArgumentException(
                    "The birthDay is before Now.It's unbelievable!");
        }
        int yearNow = cal.get(Calendar.YEAR);  //当前年份
        int monthNow = cal.get(Calendar.MONTH);  //当前月份
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH); //当前日期
        cal.setTime(birthDay);
        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
        age = yearNow - yearBirth;   //计算整岁数
        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) age--;//当前日期在生日之前，年龄减一
            } else {
                age--;//当前月份在生日之前，年龄减一
            }
        }
        return age;
    }

    /**
     * 计算年龄
     */
    public static int calculateAge(String str){
        int birthday = Integer.parseInt(str.substring(0, 4));
        int now = Integer.parseInt(Comm.getSysDate(3).substring(0, 4));
        return now - birthday;
    }

    /**
     * 昵称第二位加*号
     */
    public static String addStarToStr(String nikeName){
        StringBuilder sn = new StringBuilder(nikeName);
        if (nikeName.length() == 1){
            nikeName += "*";
        }else {
            sn.replace(1,2,"*");
            nikeName = sn.toString();
        }
        return nikeName;
    }

    /**
     * 获取本月第一天
     */
    public static Date getMonthFirstDay(){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.DAY_OF_MONTH,1);
        calendar.add(Calendar.MONTH,0);
        calendar.set(Calendar.HOUR_OF_DAY,0);
        calendar.set(Calendar.MINUTE,0);
        calendar.set(Calendar.SECOND,0);
        return calendar.getTime();
    }

    /**
     * 获取本月最后一天
     */
    public static Date getMonthLastDay(){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.DAY_OF_MONTH,0);
        calendar.add(Calendar.MONTH,1);
        calendar.set(Calendar.HOUR_OF_DAY,23);
        calendar.set(Calendar.MINUTE,59);
        calendar.set(Calendar.SECOND,59);
        return calendar.getTime();
    }

    /**
     * 获取UUID随机数
     */
    public static String getUUID(){
        String uuId = UUID.randomUUID().toString();
        return uuId.replaceAll("-","");
    }




}
